export default function($, layElement) {
  function SideMenu() {
    this.$el = null;
    this.config = {
      el  : '',
      data: null
    };
  }

  const conf = SideMenu.setter = {
    id         : 'layadmin-navmenu',
    maxCount   : 99,
    keyId      : 'id',
    keyLabel   : 'label',
    keyIcon    : 'icon',
    keyChildren: 'children',
    keyPath    : 'path',
    keySpread  : 'spread',
    keyCount   : 'count'
  };

  function handleRender(array) {
    function _render(data, level) {
      const l = data.length;
      let i = -1;
      let html = level
        ? `<dl class="layui-nav-child" role="submenu">`
        : `<ul class="layui-nav layui-nav-tree" lay-filter="${conf.id}" role="menu">`;

      while (++i < l) {
        const item = data[i];
        const id = item[conf.keyId];
        const label = item[conf.keyLabel];
        const icon = item[conf.keyIcon];
        const path = item[conf.keyPath];
        const children = item[conf.keyChildren];
        const spread = item[conf.keySpread];
        const count = item[conf.keyCount] > conf.maxCount ? '99+' : item[conf.keyCount];
        const pl = 45 + (level - 1) * 15;

        const innerHtml = [
          `<a layadmin-href="${path}" ${level ? `style="padding-left:${pl}px"` : `layadmin-tip="${label}"`}>`,
          icon ? `<i class="${icon}"></i>` : '',
          `<cite>${label}</cite>`,
          count ? `<span class="layadmin-nav-item-count">${count}</span>` : '',
          '</a>',
          children && children.length ? _render(children, level + 1) : ''
        ].join('');

        html += level
          ? `<dd data-name="${id}">${innerHtml}</dd>`
          : `<li class="layui-nav-item${spread ? ' layui-nav-itemed' : ''}" data-name="${id}">${innerHtml}</li>`;
      }

      html += level ? '</dl>' : '</ul>';
      return html;
    }
    return _render(array, 0);
  }

  SideMenu.prototype.configure = function(options) {
    $.isPlainObject(options) && $.each(options, function(key, value) {
      if (value != null) {
        conf[key] = value;
      }
    });
  };

  SideMenu.prototype.render = function(options) {
    this.config = $.extend({}, conf, options);
    this.$el = $(this.config.el);

    if (!this.$el.length) return;
    if (!$.isArray(this.config.data)) return;

    this.$el.html(this.$el.html() + handleRender(this.config.data));
    layElement.render('nav', conf.id);
  };

  return SideMenu;
}
